package com.luck.easyfoodbatch.ui;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.ShopManageAdapter;
import com.luck.easyfoodbatch.dialog.ActionSheetDialog;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.entity.ShopInfo;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.mine.DownDelGoodsModel;
import com.luck.easyfoodbatch.mvp.mine.DownDelGoodsPresenter;
import com.luck.easyfoodbatch.mvp.mine.DownDelGoodsView;
import com.luck.easyfoodbatch.mvp.mine.MyGoodsModel;
import com.luck.easyfoodbatch.mvp.mine.MyGoodsPresenter;
import com.luck.easyfoodbatch.mvp.mine.MyGoodsView;
import com.luck.easyfoodbatch.mvp.model.DownDel;
import com.luck.easyfoodbatch.mvp.model.MyGoods;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyrecyclerview.EasyRecyclerView;
import com.luck.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopManagementActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener, MyGoodsView, DownDelGoodsView {

    @BindView(R.id.rb_sort)
    RadioButton rbSort;
    @BindView(R.id.rb_volume)
    RadioButton rbVolume;
    @BindView(R.id.rb_price)
    RadioButton rbPrice;
    @BindView(R.id.rb_screen)
    RadioButton rbScreen;
    @BindView(R.id.rgbs)
    RadioGroup rgbs;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    @BindView(R.id.btn_exchange)
    Button btnExchange;
    @BindView(R.id.right_title)
    TextView right_title;
    private ShopManageAdapter adapter;
    private List<MyGoods.DataBean.ModelsBean> list = new ArrayList<>();
    private MyGoodsModel goodsModel;
    private int totalPage = 1;
    private int page = 1;
    private int isRefresh = 0;// 0普通请求，1下拉刷新，2上拉加载
    private String where = "";
    private DownDelGoodsModel delGoodsModel;
    public MyGoods.DataBean.ModelsBean data;
    private String is_expiring = "0";//1正期(暂时没好)，0不选
    // 1是客服权限只能访问我的商品和消息模块（商品和聊天）
    // 2是运营，只能访问我的商品模块（管理商品
    // 3是财务，只能访问商家信息模块（支付） ,也有可能同时兼备多个权限，（1,2就代表既是客服也是运营）
    private String role = "0";
    private List<Integer> roles = new ArrayList<>();// 权限标识

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_management, "商品管理", "编辑", MODE_BACK_NAVIGATION);
        App.getInstance().addActivity(ShopManagementActivity.this);
        ButterKnife.bind(this);
        user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        role = user.getRole();
        roles.clear();
        String[] split = role.split(",");
        for (String code : split) {
            if (!Tools.isNull(code)) {
                roles.add(Integer.parseInt(code));
            }
        }

        goodsModel = new MyGoodsPresenter(this, mContext);
        showProgressDialog(getString(R.string.app_loading));
        goodsModel.myGoodsList(page, where, is_expiring);
        LinearLayoutManager gridManager = new LinearLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5F), getResources().getColor(R.color.line_color)));
        recyclerView.setLayoutManager(gridManager);
        adapter = new ShopManageAdapter(mContext, onClick);
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                MyGoods.DataBean.ModelsBean bean = list.get(position);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("gid", bean.getGid() + "");
                intent.putExtras(bundle);
                intent.setClass(mContext, ShopDetailsActivity.class);
                startActivityForResult(intent, 300);
            }
        });
        adapter.addAll(list);
        recyclerView.setAdapter(adapter);
        recyclerView.setRefreshListener(this);
    }

    @Override
    public void rightClick() {
        super.rightClick();
        // 1. 2是运营可以进我的商品并操作 1是客服能进我的商品不能操作
        if (roles.size() > 1) {
            // 组合权限
            if (roles.contains(1) && roles.contains(2)) {
                // 运营 客服同时存在 可以操作商品
                String txt = right_title.getText().toString().trim();
                if (txt.equals("编辑")) {
                    // 编辑
                    right_title.setText("取消");
                    for (MyGoods.DataBean.ModelsBean item : list) {
                        item.setChecked(true);
                    }
                } else {
                    // 确定
                    right_title.setText("编辑");
                    for (MyGoods.DataBean.ModelsBean item : list) {
                        item.setChecked(false);
                    }
                }
                adapter.notifyDataSetChanged();
            } else if (roles.contains(2) && !roles.contains(1)) {
                // 运营 客服同时存在 可以操作商品
                String txt = right_title.getText().toString().trim();
                if (txt.equals("编辑")) {
                    // 编辑
                    right_title.setText("取消");
                    for (MyGoods.DataBean.ModelsBean item : list) {
                        item.setChecked(true);
                    }
                } else {
                    // 确定
                    right_title.setText("编辑");
                    for (MyGoods.DataBean.ModelsBean item : list) {
                        item.setChecked(false);
                    }
                }
                adapter.notifyDataSetChanged();
            } else {
                T.showAnimToast(mContext, "抱歉，您没有操作权限~");
            }

        } else {
            if (roles.contains(1)) {
                T.showAnimToast(mContext, "抱歉，您没有操作权限~");
            } else {
                String txt = right_title.getText().toString().trim();
                if (txt.equals("编辑")) {
                    // 编辑
                    right_title.setText("取消");
                    for (MyGoods.DataBean.ModelsBean item : list) {
                        item.setChecked(true);
                    }
                } else {
                    // 确定
                    right_title.setText("编辑");
                    for (MyGoods.DataBean.ModelsBean item : list) {
                        item.setChecked(false);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 4个tab点击事件
     */
    private ShopManageAdapter.OnClick onClick = new ShopManageAdapter.OnClick() {
        @Override
        public void onClick(int type, final MyGoods.DataBean.ModelsBean bean) {
            if (!Tools.isNull(role) && role.equals("1")) {
                // 客服没有操作权限
                T.showAnimToast(mContext, "抱歉，您没有操作权限~");
                return;
            }
            final Intent intent = new Intent();
            final Bundle bundle = new Bundle();
            data = bean;
            delGoodsModel = new DownDelGoodsPresenter(ShopManagementActivity.this, mContext);
            switch (type) {
                case 1:
                    // 推广
                    bundle.putSerializable("goods", bean);
                    startAct(ExtensionActivity.class, bundle);
                    break;
                case 2:
                    // 修改
                    new ActionSheetDialog(mContext)
                            .builder()
                            .setTitle("修改商品的：")
                            .setCancelable(true)
                            .setCanceledOnTouchOutside(true)
                            .addSheetItem("基本信息", ActionSheetDialog.SheetItemColor.Blue
                                    , new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            //填写事件
                                            bundle.putString("gid", bean.getGid() + "");
                                            bundle.putInt("type", 1);
                                            intent.setClass(mContext, UploadShopInfoActivity.class);
                                            intent.putExtras(bundle);
                                            startActivityForResult(intent, 200);
                                        }
                                    })
                            .addSheetItem("商品参数", ActionSheetDialog.SheetItemColor.Blue
                                    , new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            //填写事件
                                            bundle.putString("gid", bean.getGid() + "");
                                            bundle.putInt("type", 1);
                                            intent.setClass(mContext, UploadParameterActivity.class);
                                            intent.putExtras(bundle);
                                            startActivityForResult(intent, 200);
                                        }
                                    })
                            .addSheetItem("商品详情", ActionSheetDialog.SheetItemColor.Blue
                                    , new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            //填写事件
                                            bundle.putString("gid", bean.getGid() + "");
                                            bundle.putInt("type", 1);
                                            intent.setClass(mContext, UploadGraphicDetailsActivity.class);
                                            intent.putExtras(bundle);
                                            startActivityForResult(intent, 200);
                                        }
                                    })
                            .addSheetItem("认证证书", ActionSheetDialog.SheetItemColor.Blue
                                    , new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            //填写事件
                                            int product_type = 1;
                                            String country_id = bean.getCountry_id();
                                            if (!Tools.isNull(country_id)) {
                                                if (country_id.equals("1")) {
                                                    // 国产
                                                    product_type = 1;
                                                } else {
                                                    // 进口
                                                    product_type = 2;
                                                }
                                            }
                                            bundle.putString("gid", bean.getGid() + "");
                                            bundle.putInt("type", 1);
                                            bundle.putInt("product_type", product_type);
                                            intent.setClass(mContext, UploadCertificateActivity.class);
                                            intent.putExtras(bundle);
                                            startActivityForResult(intent, 200);
                                        }
                                    })
                            .show();

                    break;
                case 3:
                    // 下架
                    showDeleteDialog(0, bean);
                    break;
                case 4:
                    // 批次
                    bundle.putString("gid", bean.getGid() + "");
                    bundle.putInt("num", bean.getNum());
                    startAct(BatchListActivity.class, bundle);
                    break;
                case 5:
                    // 删除
                    showDeleteDialog(1, bean);
                    break;
            }
        }
    };

    /**
     * 删除批次
     */
    private void showDeleteDialog(final int type, final MyGoods.DataBean.ModelsBean bean) {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                App.screenHeight / 4, R.layout.wind_base_dialog_xml, R.style.Theme_dialog);
        Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        final TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        final int status = bean.getStatus();//status =1上架2下架
        switch (type) {
            case 0:
                switch (status) {
                    case 1:
                        tv_content.setText("确定要下架该商品吗？");
                        break;
                    case 2:
                        tv_content.setText("确定要上架该商品吗？");
                        break;
                }

                break;
            case 1:
                tv_content.setText("确定要删除吗？");
                break;
        }
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                dialog.dismiss();
            }
        });

        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgressDialog(getString(R.string.app_loading));
                switch (type) {
                    case 0:
                        switch (status) {
                            case 1:
                                delGoodsModel.downDel("1", bean.getGid() + "");
                                break;
                            case 2:
                                delGoodsModel.downDel("3", bean.getGid() + "");
                                break;
                        }

                        break;
                    case 1:
                        delGoodsModel.downDel("2", bean.getGid() + "");
                        break;
                }

                dialog.dismiss();
            }
        });
        dialog.show();
    }


    @Override
    public void onLoadMore() {
        //刷新
        if (!isFastDoubleClick()) {
            isRefresh = 1;
            page++;
            if (!isNetworkConnected()) {
                adapter.pauseMore();
                return;
            }
            if (page > totalPage) {
                adapter.stopMore();
                return;
            }
            goodsModel.myGoodsList(page, where, is_expiring);
        }
    }

    @Override
    public void onRefresh() {
        if(!isFastDoubleClick()) {
            isRefresh = 0;
            page = 1;
            goodsModel.myGoodsList(page, where, is_expiring);
        }
    }

    private boolean screen = false;// 正期 临期
    private int i = 0;

    @OnClick({R.id.btn_exchange, R.id.rb_sort, R.id.rb_volume, R.id.rb_price, R.id.rb_screen})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_exchange:

                if (!Tools.isNull(role) && role.equals("1")) {
                    // 客服没有操作权限
                    T.showAnimToast(mContext, "抱歉，您没有操作权限~");
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(mContext, UploadShopInfoActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.rb_sort:
                where = "";
                is_expiring = "0";
                Tools.modifyRadioButtonDrawable(mContext, rbScreen, R.mipmap.s, 0);
                break;
            case R.id.rb_volume:
                where = "1";
                is_expiring = "0";
                Tools.modifyRadioButtonDrawable(mContext, rbScreen, R.mipmap.s, 0);
                break;
            case R.id.rb_price:
                where = "2";
                is_expiring = "0";
                Tools.modifyRadioButtonDrawable(mContext, rbScreen, R.mipmap.s, 0);
                break;
            case R.id.rb_screen:
                initMonth();
                break;
        }

        if (v.getId() != R.id.btn_exchange) {
            isRefresh = 0;
            page = 1;
            goodsModel.myGoodsList(page, where, is_expiring);
        }
    }

    /**
     * 正期
     */
    private boolean isChecked = false;

    public void initMonth() {
        if (!isChecked) {
            Tools.modifyRadioButtonDrawable(mContext, rbScreen, R.mipmap.sf, 0);
            is_expiring = "1";
            isChecked = true;
        } else {
            Tools.modifyRadioButtonDrawable(mContext, rbScreen, R.mipmap.s, 0);
            is_expiring = "0";
            isChecked = false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    // 刷新数据
                    isRefresh = 0;
                    page = 1;
                    goodsModel.myGoodsList(page, where, is_expiring);
                    break;
                case 300:
                    finish();
                    break;
            }
        }
    }

    @Override
    public void myGoodsSuccess(MyGoods model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            totalPage = model.getData().getTotalPage();
            // 下拉刷新 清空集合
            switch (isRefresh) {
                case 0:
                    list.clear();
                    list = model.getData().getModels();
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    break;
                case 1:
                    // 刷新
                    List<MyGoods.DataBean.ModelsBean> models = model.getData().getModels();
                    if (models == null) {
                        models = new ArrayList<>();
                    }
                    list.addAll(models);
                    break;
            }
            adapter.clear();
            adapter.addAll(list);
            adapter.notifyDataSetChanged();
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }

    @Override
    public void delAddressSuccess(DownDel model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                right_title.setText("编辑");
                isRefresh = 0;
                page = 1;
                goodsModel.myGoodsList(page, where, is_expiring);
            } else {
                T.showAnimToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void httpStatusError() {
        T.showToast(mContext, getString(R.string.app_http_error));
    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }

}
